import { fetchApi } from "@/request/request";
import { create } from "zustand";


type Store = {
    audio: string[] | null;      // 当前要播放的文本数组
    isPlaying: boolean;         // 是否正在播放音频
    currentIndex: number;       // 当前播放的文本索引
    setPlayAudio: (content: string[]) => void; // 播放音频的方法
    pauseAudio: () => void;     // 暂停音频播放的方法
    resumeAudio: () => void;    // 恢复音频播放的方法
    stopAudio: () => void;      // 停止音频播放的方法
};


let currentAudio: HTMLAudioElement | null = null;



let isAudioPlaying = false;  // 播放锁，防止重复播放

async function playAudio(text: string) {
    if (isAudioPlaying) {
        console.warn("Audio is already playing, skipping new request.");
        return; // 防止并发播放
    }

    isAudioPlaying = true; // 设置播放锁

    try {
        // 先加载音频数据
        const res = await fetch(`/api/translate`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ action: "read", params: { text } }),
        });

        if (!res.ok) {
            throw new Error(`Failed to fetch audio: ${res.statusText}`);
        }

        const blob = await res.blob();
        const audioUrl = URL.createObjectURL(blob);

        // 确保之前的音频已停止
        if (currentAudio) {
            currentAudio.pause();
            currentAudio.src = "";
            currentAudio = null;
        }

        // 创建新的音频
        currentAudio = new Audio(audioUrl);

        // **确保音频加载完成后再播放**
        currentAudio.oncanplaythrough = () => {
            currentAudio?.play().catch(error => console.error("Audio play error:", error));
        };

        // **监听播放结束，继续下一个音频**
        currentAudio.onended = () => {
            console.log(`Finished playing: ${text}`);
            currentAudio = null;
            isAudioPlaying = false; // 释放播放锁

            const { audio, currentIndex } = usePlayStore.getState();
            if (audio && currentIndex < audio.length - 1) {
                usePlayStore.setState({ currentIndex: currentIndex + 1 });
                playAudio(audio[currentIndex + 1]); // 递归调用播放下一个音频
            } else {
                usePlayStore.setState({ isPlaying: false });
            }
        };

    } catch (error) {
        console.error("Error in fetchAndPlayAudio:", error);
        isAudioPlaying = false; // 出错时也要释放锁
    }
}




export const usePlayStore = create<Store>()((set) => ({
    audio: null,
    isPlaying: false, // 是否正在播放
    currentIndex: 0, // 当前播放的文本索引
    setPlayAudio: (content: string[]) => {
        set({ audio: content, currentIndex: 0, isPlaying: true });
        playTextArray(content);
    },
    pauseAudio: () => {
        if (currentAudio) {
            currentAudio.pause(); // 暂停音频
            set({ isPlaying: false }); // 更新状态为暂停
        }
    },
    resumeAudio: () => {
        if (currentAudio) {
            currentAudio.play(); // 恢复播放
            set({ isPlaying: true }); // 更新状态为播放
        }
    },
    stopAudio: () => {
        if (currentAudio) {
            currentAudio.pause();
            currentAudio = null; // 释放当前音频
            set({ isPlaying: false, currentIndex: 0 }); // 重置状态
        }
    },
}));


// 按顺序播放数组中的每个文本
const playTextArray = async (textArray: string[]) => {
    for (let i = 0; i < textArray.length; i++) {
        const text = textArray[i];
        console.log(text)
        await playAudio(textArray[i]); // 等待当前音频播放完再播放下一个
    }
};

